package com.giteelou.antlr.ps.man;

import com.giteelou.antlr.ps.MyLexer;
import com.giteelou.antlr.ps.MyParser;
import org.antlr.v4.runtime.CharStreams;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.ParseTreeWalker;

/**
 * 编译器
 */
public class MyCompiler {

    static Semantics compile(String script) {
        // 词法解析
        MyLexer lexer = new MyLexer(CharStreams.fromString(script));
        CommonTokenStream tokenStream = new CommonTokenStream(lexer);
        // 语法解析
        MyParser parser = new MyParser(tokenStream);
        ParseTree tree = parser.pragma();

        // 语义解析
        ParseTreeWalker walker = new ParseTreeWalker();
        Semantics semantics = new Semantics();
        semantics.ast = tree;

        VariableScanner variableScanner = new VariableScanner(semantics);
        walker.walk(variableScanner, tree);

        TypeResolver typeResolver = new TypeResolver(semantics);
        walker.walk(typeResolver, tree);

        return semantics;
    }

}
